<?php
namespace pt;

class Curl {
    static $userAgent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)';
    static $timeout = 5;
    static function get($url,$query = array()){
        if(!empty($query)){
            if(is_array($query)){
                $url .= "?".http_build_query($query);
            }
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_USERAGENT, self::$userAgent);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, self::$timeout);
        curl_setopt($ch, CURLOPT_TIMEOUT, self::$timeout);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        $data = curl_exec($ch);
        $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        return ($httpcode>=200 && $httpcode<300) ? $data : null;
    }
    static function post($url,$query = array(),$isJson = false){
        if(!empty($query)){
            if(is_array($query)){
                $query = $isJson ? json_encode($isJson) : http_build_query($query);
            }
        }

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_USERAGENT, self::$userAgent);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, self::$timeout);
        curl_setopt($ch, CURLOPT_TIMEOUT, self::$timeout);

        if(!empty($query))
            curl_setopt($ch, CURLOPT_POSTFIELDS, $query);

        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_POST, 1);

        $data = curl_exec($ch);

//        if(!curl_errno($ch)){
//            $info = curl_getinfo($ch);
//            echo 'Took ' . $info['total_time'] . ' seconds to send a request to ' . $info['url'];
//        } else {
//            echo 'Curl error: ' . curl_error($ch);
//        }

        $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        curl_close($ch);
        return ($httpcode>=200 && $httpcode<300) ? $data : null;
    }
}
